import React, { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import authManager from '../utils/auth';

interface ProtectedRouteProps {
  children: React.ReactNode;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        // 检查基本认证状态
        if (!authManager.isAuthenticated()) {
          setIsAuthenticated(false);
          return;
        }

        // 尝试获取有效token（会自动刷新）
        const validToken = await authManager.getValidAccessToken();
        setIsAuthenticated(!!validToken);
      } catch (error) {
        console.error('Auth check failed:', error);
        setIsAuthenticated(false);
      }
    };

    checkAuth();
  }, []);

  // 加载中状态
  if (isAuthenticated === null) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh'
      }}>
        验证中...
      </div>
    );
  }

  // 未认证，重定向到登录页面
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  // 已认证，渲染子组件
  return <>{children}</>;
};

export default ProtectedRoute;